package org.jeecg.modules.demo.zyExam.zypaperperson.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.zyExam.zyexamaddpaper.entity.ZyExamAddPaper;
import org.jeecg.modules.demo.zyExam.zyexamaddpaper.mapper.ZyExamAddPaperMapper;
import org.jeecg.modules.demo.zyExam.zypaperperson.entity.ZyPaperPerson;
import org.jeecg.modules.demo.zyExam.zypaperperson.mapper.ZyPaperPersonMapper;
import org.jeecg.modules.demo.zyExam.zypaperperson.service.IZyPaperPersonService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description: 试卷和人中间表
 * @Author: jeecg-boot
 * @Date: 2024-01-11
 * @Version: V1.0
 */
@Service
public class ZyPaperPersonServiceImpl extends ServiceImpl<ZyPaperPersonMapper, ZyPaperPerson> implements IZyPaperPersonService {

    @Autowired
    private ZyPaperPersonMapper zyPaperPersonMapper;

    @Autowired
    private ZyExamAddPaperMapper zyExamAddPaperMapper;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ISysUserService sysUserService;



    @Override
    public Object[] queryByPaperCode(String paperId) {
        return null;
    }
//
//        List<Map<String, Object>> scoreList = zyPaperPersonMapper.queryMaxScoreByPaperCode(paperId);
//        System.out.println(scoreList.size());
//        int passNumber = 0;
//        int examNumber = 0;
//        String score = "";
//        for (Map<String, Object> objectMap : scoreList) {
//            score = score + objectMap.get("score") + ",";
//            System.out.println(objectMap.get("score"));
//            if (objectMap.get("is_pass").equals("是")) {
//                passNumber++;
//            }
//            if (objectMap.get("is_exam").equals("是")) {
//                examNumber++;
//            }
//        }
//        System.out.println("及格人数：" + passNumber);
//        System.out.println("考试人数：" + examNumber);
//        ZyExamAddPaper one = Db.lambdaQuery(ZyExamAddPaper.class).eq(ZyExamAddPaper::getId, paperId).one();
//        String enthic_code = one.getEnthic();
//        System.out.println("enthic_code:" + enthic_code);
////        int peopleSize = Db.lambdaQuery(ZyRealName.class)
////                .eq(ZyRealName::getJobType, enthic_code)
////                .list().size();
////        System.out.println("peopleSize:" + peopleSize);
////        String enthic = zyExamAddPaperMapper.querySource(enthic_code);
////        System.out.println("enthic:" + enthic);
////        Object totals[] = {peopleSize, passNumber, examNumber, score, enthic};
////        Map<String,Object> map=new HashMap<>();
////        map.put("peopleSize",peopleSize);
////        map.put("passNumber",passNumber);
////        map.put("examNumber",examNumber);
////        map.put("score",score);
////        map.put("enthic",enthic);
////        return totals;
//        return null;
//    }
//    public Map<String, Object> queryByPaperCode1(String paperId) {
//        List<Map<String, Object>> scoreList = zyPaperPersonMapper.queryMaxScoreByPaperCode(paperId);
//        String paperName = zyExamAddPaperMapper.queryPaperName(paperId);
//        System.out.println(scoreList.size());
//        int passNumber = 0;
//        int examNumber=0;
//        String score1="";
//        String score2="";
//        String totalScore="0";
//        if (scoreList.size()>0){
//            totalScore= scoreList.get(0).get("total_score").toString();
//        }
//        for (Map<String, Object> objectMap : scoreList) {
//
//            System.out.println(objectMap.get("score"));
//            if (objectMap.get("is_pass").equals("是")) {
//                passNumber++;
//            }
//            if (objectMap.get("is_exam").equals("是")){
//                examNumber++;
//                score1=score1+objectMap.get("score")+",";
//            }
//            if (objectMap.get("is_exam").equals("否")){
//                 score2=score2+objectMap.get("score")+",";
//            }
//        }
//        System.out.println("及格人数："+passNumber);
//        System.out.println("考试人数："+examNumber);
//        ZyExamAddPaper one = Db.lambdaQuery(ZyExamAddPaper.class).eq(ZyExamAddPaper::getId, paperId).one();
////        int peopleSize = Db.lambdaQuery(ZyRealName.class)
////                .eq(ZyRealName::getJobType, enthic_code)
////                .list().size();
////        System.out.println("peopleSize:" + peopleSize);
////        Object totals[] = {peopleSize,passNumber,examNumber,score1,score2,enthic};
//        Map<String,Object> map=new HashMap<>();
////        map.put("peopleSize",peopleSize);
//        map.put("passNumber",passNumber);
//        map.put("examNumber",examNumber);
//        map.put("score",score1);
//        map.put("score2",score2);
//        map.put("totalScore",totalScore);
//        map.put("paperName",paperName);
//        return map;
//    }

public Map<String, Object> queryByPaperCode1(String paperId) {
    List<Map<String, Object>> scoreList = zyPaperPersonMapper.queryMaxScoreByPaperCode(paperId);
    String paperName = zyExamAddPaperMapper.queryPaperName(paperId);
    String scorePass = zyExamAddPaperMapper.querySourcePass(paperId);
    System.out.println(scoreList.size());
    int passNumber = 0;
    int examNumber = 0;
    StringBuilder score1 = new StringBuilder();
    StringBuilder score2 = new StringBuilder();
    String totalScore = "0";
    if (scoreList.size() > 0) {
        totalScore = scoreList.get(0).get("total_score").toString();
    }
    for (Map<String, Object> objectMap : scoreList) {
        System.out.println(objectMap.get("score"));
        if (objectMap.get("is_pass").equals("是")) {
            passNumber++;
        }
        if (objectMap.get("is_exam").equals("是")) {
            examNumber++;
            score1.append(objectMap.get("score")).append(",");
        }
        if (objectMap.get("is_exam").equals("否")) {
            score2.append(objectMap.get("score")).append(",");
        }
    }
    // 去除最后一个逗号
    if (score1.length() > 0) {
        score1.setLength(score1.length() - 1);
    }
    if (score2.length() > 0) {
        score2.setLength(score2.length() - 1);
    }
    System.out.println("及格人数：" + passNumber);
    System.out.println("考试人数：" + examNumber);
    ZyExamAddPaper one = Db.lambdaQuery(ZyExamAddPaper.class).eq(ZyExamAddPaper::getId, paperId).one();
    Map<String, Object> map = new HashMap<>();
    map.put("passNumber", passNumber);
    map.put("examNumber", examNumber);
    map.put("score", score1.toString());
    map.put("score2", score2.toString());
    map.put("totalScore", totalScore);
    map.put("paperName", paperName);
    map.put("scorePass", scorePass);
    return map;
}

    @Override
    public void deleteByPaperCode(String id) {
        zyPaperPersonMapper.deleteByPaperCode(id);
    }


    @Override
    @Transactional
    public void saveAll(ZyExamAddPaper zyExamAddPaper) {
        List<SysUser> sysUsersList = new ArrayList<>();
        // 如果flag是1，则查询所有用户
        if(zyExamAddPaper.getFlag().equals("1")){
         sysUsersList = Db.lambdaQuery(SysUser.class)
                .list();
            System.out.println("sysUsersList = " + sysUsersList);
        }else{
            String userName = zyExamAddPaper.getPersonName();
            System.out.println("userName = " + userName);
            //遍历userName，逗号隔开，用 List<SysUser>集合接收
            String[] userNames = userName.split(",");
            for (String userName1 : userNames) {
                SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getRealname, userName1));
                System.out.println("sysUser = " + sysUser);
                sysUsersList.add(sysUser);
            }

        }
//            List<SysUser> sysUsersList=zyExamAddPaper.getPaperName();
        // 批量插入准备
        List<ZyPaperPerson> paperPersonList = new ArrayList<>();
        // 消息推送准备
        List<MessageDTO> messageDTOs = new ArrayList<>();
        // 用户名收集
        StringBuilder userNames = new StringBuilder();

        // 将 java.util.Date 转换为 LocalDateTime 并格式化输出
        LocalDateTime localDateTime = zyExamAddPaper.getExamDate().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = localDateTime.format(outputFormat);

        for (SysUser sysUser  : sysUsersList) {
            ZyPaperPerson zyPaperPerson = new ZyPaperPerson();
            zyPaperPerson.setName(sysUser.getRealname());
            zyPaperPerson.setExamDate(zyExamAddPaper.getExamDate());
            zyPaperPerson.setIsExam("否");
            zyPaperPerson.setJudgeQuestionNumber(zyExamAddPaper.getJudgeQuestionNumber());
            zyPaperPerson.setMutilQuestionNumber(zyExamAddPaper.getMutilQuestionNumber());
            zyPaperPerson.setMutilChoiceQuestionNumber(zyExamAddPaper.getMutilChoiceQuestionNumber());
            zyPaperPerson.setFillQuestionNumber(zyExamAddPaper.getFillQuestionNumber());
            zyPaperPerson.setPaperId(zyExamAddPaper.getId());
            zyPaperPerson.setSource(zyExamAddPaper.getSource());  // 注意这里可能有重复设置source的问题，请检查
            zyPaperPerson.setIsPass("");
            zyPaperPerson.setTotalScore(zyExamAddPaper.getTotalScore());
            zyPaperPerson.setScore(0);
            zyPaperPerson.setSource(zyExamAddPaper.getPaperName()); // 再次设置source，确保是预期的行为
            zyPaperPerson.setSiteId(zyExamAddPaper.getSiteId());

            String userByRealName = sysUserService.getUserByReamName(sysUser.getRealname());
            if (userNames.length() > 0) {
                userNames.append(", ");
            }
            userNames.append(userByRealName);

            paperPersonList.add(zyPaperPerson);
        }
        // 执行批量插入
        saveBatch(paperPersonList); // 假设有一个batchInsert方法
        MessageDTO messageDTO = new MessageDTO("系统",
                userNames.toString(),
                "考试提醒",
                "您有一场" + zyExamAddPaper.getPaperName() + "考试，考试时间为：" + formattedTime + "请准时参加!!!");
        // 发送批量消息
        sysBaseAPI.sendSysAnnouncement(messageDTO); // 假设有sendSysAnnouncements方法支持批量发送
    }

    @Override
    public boolean getByName(String realname) {
        String id = zyPaperPersonMapper.getByName(realname);
        if (id == null) {
            return true;
        }
        return false;

    }

    @Override
    public String editByNameAndPaperId(ZyPaperPerson zyPaperPerson) {
        String s="";
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String name = loginUser.getRealname();
        ZyPaperPerson zyPaperPerson1 = zyPaperPersonMapper.editByNameAndPaperId(zyPaperPerson.getPaperId(), name);
//        zyPaperPerson.setScore(22);
        if (zyPaperPerson1 != null) {
            if (zyPaperPerson1.getScore() < zyPaperPerson.getScore()) {
                zyPaperPerson1.setScore(zyPaperPerson.getScore());
                zyPaperPerson1.setMutilQuestionAnswer(zyPaperPerson.getMutilQuestionAnswer());
                zyPaperPerson1.setMutilChoiceQuestionAnswer(zyPaperPerson.getMutilChoiceQuestionAnswer());
                zyPaperPerson1.setJudgeQuestionAnswer(zyPaperPerson.getJudgeQuestionAnswer());
                zyPaperPerson1.setFillQuestionAnswer(zyPaperPerson.getFillQuestionAnswer());
                zyPaperPerson1.setIsPass(zyPaperPerson.getIsPass());
                System.out.println("zyPaperPerson.getIsPass() = " + zyPaperPerson.getIsPass());
                if (zyPaperPerson.getIsPass().equals("否")) {
                    System.out.println("loginUser.getUsername() = " + loginUser.getUsername());
                    MessageDTO message = new MessageDTO("系统",  loginUser.getUsername(),
                            "考试信息推送", "本次考试成绩不及格，下次继续努力！");
                    sysBaseAPI.sendSysAnnouncement(message);
                }
                zyPaperPerson1.setIsExam(zyPaperPerson.getIsExam());
                zyPaperPersonMapper.updateById(zyPaperPerson1);
                s= "成绩更新成功！";
            }
            s="提交试卷成功";
        } else {
            s= "您没有这场考试,没有考试成绩！";
        }
        return s;
    }





}
